<template>
    <div class="upload-container">
        <div class="upload_buttom">
        <el-button :style="{background:color,borderColor:color}" icon="el-icon-upload" size="mini" type="primary" @click="addimglist">
            插入图库图片
        </el-button>
        <el-button :style="{background:color,borderColor:color}" icon="el-icon-upload" size="mini" type="primary" @click=" dialogVisible=true">
            上传本地图片
        </el-button>
        </div>

        <el-dialog :visible.sync="dialogVisible" append-to-body>
            <el-upload
                action=""
                :multiple="true"
                :auto-upload="false"
                list-type="picture-card"
                :on-preview="handlePictureCardPreview"
                :on-remove="handleRemove"
                :on-change="handProgress"
                :file-list="imageUrl"
                >
                <i class="el-icon-plus"></i>
            </el-upload>
            <div style="margin-top:50px;text-align:center;">
                 <el-button type="primary" @click="onSubmit">确 定</el-button>
                 <el-button @click="cancel">取 消</el-button>
            </div> 
        </el-dialog>
        <el-dialog :visible.sync="dialogFileVisible" append-to-body  width="1008px" :title="'插入图库图片'">
            <picture-html @checkPicture="checkPicture" @cancelPicture="function(){return dialogPictureVisible=false;} " :limits="15" :isPrivate="isPrivate"></picture-html>
        </el-dialog>    
          <el-dialog :visible.sync="dialogImgVisible">
            <el-carousel
                v-if="dialogImgVisible"
                :initial-index="imgInx"
                arrow="always"
                :autoplay="false"
                style="height: 400px"
            >
                <el-carousel-item
                v-for="item in imageUrl"
                :key="item.uid"
                style="height: 400px"
                >
                <img style="width: 100%; height: 100%" :src="item.url" alt="" />
                </el-carousel-item>
            </el-carousel>
        </el-dialog>
    </div>
</template>
<script>
import * as qiniu from "qiniu-js";
import Md5 from "crypto-js/md5.js";
import {
  getQiNiuToken,
  getQiNiuImagePath,
  getPrivateImagePath,
} from "@/api/common";

export default {
    components:{
        pictureHtml: () => import("@/widgets/xdh-form/items/upload/src/picture.vue"),
    },
    props: {
        color: {
        type: String,
        default: '#1890ff'
        },
        prop: {
        type: String,
        default: ''
        },
        labels: {
        type: String,
        default: '封面图片'
        }
    },
    data(){
        return {
            dialogImgVisible:false,
            dialogVisible: false,
            dialogFileVisible: false,
            isPrivate:0,
            imageUrl: [],
            imagePath: "",
            imgInx:0
        }
    },
     methods: {
        addimglist() {
            this.dialogFileVisible = true;
        },
        checkPicture(item){
            this.$emit('successCategory',item);
            this.dialogFileVisible=false;
        },
        //上传七牛
        handProgress(file, fileList) {
        let that = this;
        this.getToken(file, function (res, state) {
            if (!state) {
            return false;
            }

            that.token = res.token;
            that.hostUrl = res.hostUrl;

            let key = Md5(new Date().getTime()).toString() + file.name;
            let token = res.token;
            let putExtra = {};
            let config = {
                useCdnDomain: true,
                disableStatisticsReport: false,
                retryCount: 6,
                region: qiniu.region.z2,
            };

            const observable = qiniu.upload(file.raw, key, token, putExtra, config);

            const subscription = observable.subscribe({
            next: function (res) {
                if (res.total.percent == 100) {
                that.percentage = 0;
                } else {
                that.percentage = res.total.percent;
                }
            },
            error: function (res) {
                console.log(res);
            },
            complete: function (res) {
                var fileArr = {
                    img_path: that.hostUrl + "/" + res.key,
                    name: file.raw.name,
                    is_private: that.$attrs.isPrivate,
                    path: res.key,
                    hash: res.hash,
                    host: that.hostUrl,
                    type: file.raw.flag,
                    size: file.raw.size,
                    route: that.$route.path,
                    };
                    that.percentage = 0;
                    that.getImagePath(fileArr);
                },
            });
        });
        },
        //获得七牛token
        async getToken(file, callback) {
            let params = {
                filename: file.name,
                type: file.raw.type,
                size: file.raw.size,
                is_private: this.isPrivate,
            };
            const res = await getQiNiuToken(params);
            if (res.code == 200) {
                return callback(res.data, true);
            }

            this.assemblingParam(res);
            return callback(res.data, false);
        },
        //上传服务器
        getImagePath: async function (obj) {
            const res = await getQiNiuImagePath(obj);
            if (res.code == 200) {
                this.assemblingParam(res, obj.name);
            }
        },
        //组装图片参数
        assemblingParam(res, filename) {
            var newPath = this.imagePath ? this.imagePath.split(",") : [];

            newPath.push(res.data.path);

            this.imagePath = newPath.join(",");

            if (filename) {
                res.data.name = filename;
            }
            

            this.imageUrl.push(res.data);
        },

        //查看图片
        handlePictureCardPreview(file) {
            var that = this;
            this.imageUrl.forEach((item, inx) => {
                if (item.name == file.name) {
                that.imgInx = inx;
                }
            });
            this.dialogImgVisible = true;
        },
        //删除图片
        handleRemove(file, fileList) {
            let newPath = [];
            let newCoverId = [];

            for (var i in fileList) {
                newPath.push(fileList[i].path);
                newCoverId.push(fileList[i].cover_id);
            }

            this.imagePath = newPath.join(",");
            this.coverId = newCoverId.join(",");

            this.imageUrl = fileList;

            this.$emit("input", this.coverId);
        },
        onSubmit(){
            this.$emit('successCategory',this.imageUrl);
            this.dialogVisible=false;
        },
        cancel(){
            this.dialogVisible=false;
        }
    }
}
</script>